package elas

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"rpc-server/basic/global"
	"rpc-server/internal/model"
	__ "rpc-server/proto"
	"strconv"
	"sync"
)

func SyncGoodsToEs() {

	var wg sync.WaitGroup

	var goodList []*model.Good
	//写不写都能出
	//var g model.Good
	//
	//global.DB.Find(g)

	for _, good := range goodList {
		wg.Add(1)

		go func(good *model.Good) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(good)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "good",
				DocumentID: strconv.Itoa(int(good.Id)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), global.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(good)
	}
	wg.Wait()

}

func SearchGood(keyword string) (goodsList []*__.GoodsItem) {
	var buf bytes.Buffer

	var query map[string]interface{}

	if keyword != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodTitle": keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}

	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := global.Es.Search(
		global.Es.Search.WithContext(context.Background()),
		global.Es.Search.WithIndex("good"),
		global.Es.Search.WithBody(&buf),
		global.Es.Search.WithTrackTotalHits(true),
		global.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	var r map[string]interface{}
	if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}

	// Print the ID and document source for each hit.
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		m := hit.(map[string]interface{})["_source"].(map[string]interface{})
		f := m["ID"].(float64)
		goodsList = append(goodsList, &__.GoodsItem{
			GoodsId:    int64(f),
			GoodsTitle: "",
			GoodsPrice: 0,
			GoodsCover: "",
		})

	}

	fmt.Println(goodsList)

	return

}
